<?php

include('cfg/def.php');
include('cfg/cfg.php');

include_once("lib/logger.class.php");
include_once("lib/mysql.class.php");
include_once("lib/utils.class.php");

Logger::$log_file = "logs/ajax";

MySQL::$url = $dburl;
MySQL::$encoding = $def_encoding;

session_start();

if(DEBUG_MODE && FALSE)
{
	Logger::Write(__FILE__." line ".__LINE__, '$_GET: '.print_r($_GET, true));
	Logger::Write(__FILE__." line ".__LINE__, '$_POST: '.print_r($_POST, true));
}

$xml = $_POST["xml"];
$xml = stripslashes($xml);
Logger::Write(__FILE__." line ".__LINE__, 'AJAX REQUEST: '.$xml);

// Пакет ответа
$pack_a = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><pack />');
try
{
	// Пакет запроса
	$pack_r = new SimpleXMLElement($xml);
	foreach($pack_r->request as $req)
	{
		if(DEBUG_MODE) Logger::Write(__FILE__." line ".__LINE__, "object: ".$obj_name." action: ".$act_type);
		
		$obj_name  = strtolower($req["obj"]);
		if($obj_name != 'city') break;
		
		$act_type  = $req["act_type"];
		$page_type = $req["page_type"];
		$html      = $req["html"];
		
		$data = nodes2arr($req->data);
		$cond = nodes2arr($req->cond);
		$opt  = nodes2arr($req->option);
		
		$ans = $pack_a->addChild("ans");
		$ans->addAttribute("req_id", $req["id"]);
		$ans_error = "0";
		
		$cities = getCities($cond["name"]);
		foreach($cities as $city)
		{
			$cityX = $ans->addChild("city");
			$cityX->addAttribute("id", $city["id"]);
			$cityX->addAttribute("name", $city["name"]);
			$cityX->addAttribute("region", $city["region"]);
			$cityX->addAttribute("population", $city["population"]);
		}
	}
}
catch(Exception $e)
{
	$msg = "CLASS: ".$e->class."\nMESSAGE: ".$e->getMessage();
	// $msg = print_r($e, TRUE);
	$ans = $pack_a->addChild("ans");
	$e = $ans->addChild("error", htmlspecialchars_decode($msg));
}

$xml = $pack_a->asXML();
$xml = str_replace('&lt;![CDATA[', '<![CDATA[', $xml);
$xml = str_replace(']]&gt;', ']]>', $xml);

if(DEBUG_MODE)
{
	global $log_file_name;
	$fd = fopen($log_file_name.".xml.".date('Ymd').".log", "w+");
	fwrite($fd, $xml);
	fclose($fd);
}

header('Content-Type: text/xml; charset=utf-8');
echo $xml;

exit();

function getCities($cityName)
{
	$db = MySQL::getInstance();
	$cities = array();

	$sql =
		"SELECT c.id, c.name name, r.name region, c.population
		   FROM cities c, regions r
		  WHERE c.region_id = r.id
			AND c.name like '$cityName%'";

	if(LOG_SQL) Logger::Write(__FILE__." line ".__LINE__, $sql);
	$res = $db->query($sql);
	while($row = $db->fetch_assoc($res))
	{
		$cities[] = $row;
	}
	$db->free_result($res);
	return $cities;	
}

function nodes2arr($nodes)
{
	$a = array();
	if(empty($nodes)) return $a;
	foreach($nodes as $child)
		$a[(string)$child["name"]] = html_entity_decode(Utils::val((string)$child["value"]), ENT_QUOTES);
	return $a;
}